﻿(function ($) {

    "use strict";

    $.jSPCSOM = $.jSPCSOM || { };

    $.jSPCSOM.getListData = function (options) {

        var defaultOptions = {
            listName: null,
            viewXml: "<View><RowLimit>100</RowLimit></View>",
            includeFields: null,
            includeStatement: null
        };

        options = $.extend({}, defaultOptions, options);

        var dataLoaded = $.Deferred();

        if (options.listName == null || options.viewXml == null) throw "List Name and View XML are required fields";
        console.log("You made it here.");

        var includeText = "";
        if (options.includeStatement != null) {
            includeText = options.includeStatement;
        }
        else if (options.includeFields != null && options.includeFields.length > 0) {
            includeText = "Include(";
            for (var i = 0; i < options.includeFields.length; ++i) {
                if (i > 0)
                    includeText += ",";

                includeText += options.includeFields[i];
            }
            includeText += ")";
        }

        var context = SP.ClientContext.get_current();
        var list = context.get_web().get_lists().getByTitle(options.listName);
        var camlQuery = new SP.CamlQuery();
        camlQuery.set_viewXml(options.viewXml);

        var listItems = list.getItems(camlQuery, includeText);

        context.load(listItems);
        context.executeQueryAsync(function () {
            dataLoaded.resolve({
                dataLoadSuccess: true,
                message: "Items for list " + options.listName + " loaded successfully",
                data: listItems
            })
        },
        function () {
            dataLoaded.resolve({
                dataLoadSuccess: false,
                message: "Failed to load items for list " + options.listName,
                data: null
            });
        });

        return dataLoaded;
    }

    $.jSPCSOM.execute = function (options) {
        var defaultOptions = {
            clientContext: SP.ClientContext.get_current(),
            data: null
        };
        options = $.extend({}, defaultOptions, options);

        var dataLoaded = $.Deferred();

        options.clientContext.executeQueryAsync(function () {
            dataLoaded.resolve({
                loadedSuccess: true,
                message: "Items for list " + options.listName + " loaded successfully",
                data: options.data
            })
        },
        function () {
            dataLoaded.resolve({
                loadedSuccess: false,
                message: "Items for list " + options.listName + " loaded successfully",
                data: options.data
            })
        });
        
        return dataLoaded;
    };
})(jQuery);
